package com.example.im.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import com.example.im.common.ImApplication

class NetworkBroadcastReceiver : BroadcastReceiver() {

    private var netStatusListener: OnNetStatusListener? = null

    override fun onReceive(context: Context?, intent: Intent?) {

        if (intent == null)
            return

        if (intent.action != ConnectivityManager.CONNECTIVITY_ACTION)
            return

        if (netStatusListener != null)
            netStatusListener!!.onNetChange(isNetworkState())
    }


    private fun isNetworkState(): Boolean {

        val connManager =
            ImApplication.context().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        val networkInfo = connManager.activeNetworkInfo

        return networkInfo != null && networkInfo.isConnected
    }

    interface OnNetStatusListener {
        fun onNetChange(netStatus: Boolean)
    }

    fun setOnNetStatusListener(netStatusListener: OnNetStatusListener) {
        this.netStatusListener = netStatusListener
    }

}